package com.uzai.console.service.remoteapi.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.entity.CdkeysMobileApp;
import com.uzai.console.mapper.CdkeysMobileAppMapper;
import com.uzai.console.para.DeviceMobileSofyAuthRemoteApiPara;
import com.uzai.console.service.remoteapi.DeviceRemoteApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * @Auther: liuqi
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class DeviceRemoteApiServiceImpl implements DeviceRemoteApiService {

    private static Logger logger = LoggerFactory.getLogger(DeviceRemoteApiServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private CdkeysMobileAppMapper cdkeysMobileAppMapper;

    /**
     * 远程调用机器人移动端授权接口
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param deviceMobileAuthRemoteApiPara
     * @return null
     */
    public Boolean deviceMobileSoftAuth(DeviceMobileSofyAuthRemoteApiPara deviceMobileAuthRemoteApiPara, Integer deviceTypeId){

        Boolean flag = false;

        try{
            String authUrl = uzaiConsoleSysConfig.getDeviceMobileAuthUrl();
            MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
            param.add("cid", Const.Device.MOBILE_APP_CID);
            if(Tools.getInteger(deviceTypeId).intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT_VALUE){  //个微
                param.add("packageName", Const.Device.MOBILE_APP_PACKAGENAME);
            }else if(Tools.getInteger(deviceTypeId).intValue() == DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE){ //企微
                param.add("packageName", Const.Device.MOBILE_APP_PACKAGENAME_WXWORK);
            }
            param.add("expire_time", DateFormatUtil.format(new Date(deviceMobileAuthRemoteApiPara.getExpireTime()*1000L), "yyyy-MM-dd"));
            param.add("imei", deviceMobileAuthRemoteApiPara.getImei());
            param.add("regCode", deviceMobileAuthRemoteApiPara.getRegCode());

            logger.info("---调用手机端APP卡密授权请求参数--para={}", JSONObject.toJSONString(param));

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(authUrl, request, JSONObject.class);
            if (response.getStatusCode() != HttpStatus.OK){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
            JSONObject jsonObject = response.getBody();
            logger.info("---调用手机端APP卡密授权--para={},result={}", JSONObject.toJSONString(param), JSONObject.toJSONString(jsonObject));

            //将日记统一保存到13160220184账号里
            logger.info(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.DEVICE_MOBILE_SOFT_AUTH_VALUE,
                    1157181383497326594L, 1, null,
                    "", 0L,
                    JSONObject.toJSONString(param)+ ";" + JSONObject.toJSONString(jsonObject))));

            if(Integer.parseInt(jsonObject.get("bizCode").toString()) == 0){ //授权成功
                flag = true;
            }else{
                CdkeysMobileApp cdkeysMobileApp = cdkeysMobileAppMapper.selectByCard(deviceMobileAuthRemoteApiPara.getRegCode());
                cdkeysMobileApp.setDeviceId(null);
                cdkeysMobileApp.setStatus(2);//异常卡,激活码已被使用
                cdkeysMobileApp.setExpireTime(null);
                cdkeysMobileApp.setTradeno(null);
                cdkeysMobileAppMapper.updateById(cdkeysMobileApp);
                flag = false;
            }
        }catch (Exception e){
            logger.info("--device mobile app auth request error..deviceId={},error={}", deviceMobileAuthRemoteApiPara.getImei(),e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
        }
        return flag;
    }

}
